/**
 * 
 */
const loginPwdUtil = require('./util/loginPwdUtil');
const db = require('./db');

exports.doRegister = (req, resp) => {
    let param = req.body;
    let pwd1 = param.password;
    let pwd2 = param.password2;
    if (pwd1 !== pwd2) {
        resp.set('Content-Type', 'text/json; charset=utf8');
        resp.send('两次密码输入不一致！');
        return;
    }
    let _salt = loginPwdUtil.salt();
    let sql = 'INSERT INTO t_user SET ?';
    let data = {
        name: param.name,
        password: loginPwdUtil.encrypt(pwd1, _salt),
        salt: _salt,
        createtime: loginPwdUtil.now()
    };
    db.base(sql, data, (err, results, fields)=>{
        if (err) throw err;
        if (results.affectedRows === 1) {
            resp.redirect('/index');
        } else {
            resp.set('Content-Type', 'text/json; charset=utf8');
            resp.send('注册失败，请联系管理员！');
        }
    });
};

exports.doLogin = (req, resp) => {
    let param = req.body;
    let pwd = param.password;
    let username = param.name;

    // 这里也可以使用 select count(1) from t_user where name = ? and password = ?
    // 但是要查询 salt , 所以使用 select * from t_user where name = ? 还是最优的方案。
    let sql = 'SELECT * FROM t_user WHERE name = ?';
    db.base(sql, username, (err, results, fields)=>{
        if (err) throw err;
        if (results && results[0].name) {
            let salt = results[0].salt;
            let password = results[0].password;
            let pwdEncrypt = loginPwdUtil.encrypt(pwd, salt);
            if (password !== pwdEncrypt) {
                resp.set('Content-Type', 'text/json; charset=utf8');
                resp.send('登录失败，请联系管理员！');
            } else {
                resp.redirect('/index');
            }
        } else {
            resp.set('Content-Type', 'text/json; charset=utf8');
            resp.send('登录失败，请联系管理员！');
        }
    });
};